package com.ak.utils;

import com.ak.entity.Rows;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bn
 */
public class ConnectUtils {

    public static String USER_AGENT = "User-Agent";
    public static String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";


    /**
     * 转发
     * @param url
     * @return
     */
    public static Connection.Response responseJson(String url, Connection.Response res)  {
        Connection con = Jsoup.connect(url)
                .header(USER_AGENT, USER_AGENT_VALUE)
                .header("Accept", "application/json, text/javascript, */*; q=0.01")
                .header("Accept-Encoding", "gzip, deflate, sdch")
                .header("Content-Type","application/json; charset=UTF-8");
        try {
            return con.ignoreContentType(true).
                    followRedirects(true).
                    method(Connection.Method.POST).
                    cookies(res.cookies()).
                    execute();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Connection.Response response(String url, Connection.Response res)  {
        Connection con = Jsoup.connect(url);
        con.header(USER_AGENT, USER_AGENT_VALUE)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .header("Accept-Encoding", "gzip, deflate, sdch")
                .header("Content-Type","text/html; charset=utf-8");


        try {
            return con.ignoreContentType(true).
                    followRedirects(true).
                    method(Connection.Method.POST).
                    cookies(res.cookies()).
                    execute();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T copyAttr(Object parameter,Object  selectObj) {
        Field[] fields = parameter.getClass().getDeclaredFields();
        if(null!=fields){
            for(int i=0;i<fields.length;i++){
                Field pojo = fields[i];
                String attrName = pojo.getName();
                Object attrValue = null;
                Field rfield;
                try {
                    pojo.setAccessible(true);
                    attrValue = pojo.get(parameter);
                    rfield = selectObj.getClass().getField(attrName);
                    rfield.setAccessible(true);
                    rfield.set(selectObj,  attrValue);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }catch (NoSuchFieldException e) {
                    continue;
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }

        }
        return  (T) selectObj;
    }

    /**
     * 登陆
     */
    public static Connection.Response login(String url,String userName,String password){
        // 获取connection
        Connection con = Jsoup.connect(url);
        // 配置模拟浏览器
        con.header(USER_AGENT, USER_AGENT_VALUE);
        // 获取响应
        Connection.Response rs = null;
        try {
            rs = con.execute();
            // 转换为Dom树
            Document d1 = Jsoup.parse(rs.body());
            Map<String, String> datas = new HashMap<>();
            // 获取form 表单你
            List<Element> eleList = d1.select("form");
            // 填写 form 表单
            for(int i = 0; i < eleList.size(); i++) {

                for (Element e : eleList.get(i).getAllElements()) {
                    // 设置用户名
                    if (e.attr("name").equals("username")) {
                        e.attr("value", userName);
                    }
                    // 设置用户密码
                    if (e.attr("name").equals("password")) {
                        e.attr("value", password);
                    }
                    // 排除空值表单属性
                    if (e.attr("name").length() > 0) {
                        datas.put(e.attr("name"), e.attr("value"));
                    }
                }
            }
           return con.ignoreContentType(true)
                   .followRedirects(true)
                   // post 请求
                   .method(Connection.Method.POST)
                   // 添加密码，用户
                   .data(datas)
                   //
                   .cookies(rs.cookies())
                   .execute();

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 带参数的
     * @param url
     * @param res
     * @param data
     * @return
     */
    public static Connection.Response responseJsonParam(String url, Connection.Response res,String data)  {
        Connection con = Jsoup.connect(url)
                .header(USER_AGENT, USER_AGENT_VALUE)
                .header("Accept", "application/json, text/javascript, */*; q=0.01")
                .header("Accept-Encoding", "gzip, deflate, sdch")
                .header("Content-Type","application/json; charset=UTF-8")
                .requestBody(data)
                ;
        try {
            return con.ignoreContentType(true).
                    followRedirects(true).
                    method(Connection.Method.POST).
                    cookies(res.cookies()).
                    execute();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
